#!/usr/bin/env python
#encoding : uf-8

import sys
import re
from urlparse import urlsplit

class HandlerNotFoundException(Exception):pass


def import_handler(handle_name):
	mod_name, handle = handle_name.rsplit('.', 1)
	mod = __import__ (mod_name, globals(), locals(), [handle,])
	try:
		return getattr(mod, handle)
	except:
		raise HandlerNotFoundException('no handle named %s' % handle_name)


class Dispatcher(object):
	def __init__(self, map_list):
		self._mapping = []
		for mapping in map_list:
			match_str, handler = mapping[:2]
			other_params = mapping[2:]
			self._mapping.append((re.compile(match_str).match, handler, other_params))

	def get_handler(self, url):
		req_script = urlsplit(url)[2]
		for i, pattern in enumerate(self._mapping):
			url_match, handler, other_params = pattern
			match = url_match(req_script)
			if match is not None:
				if not callable(handler):
					handler = import_handler(handler)
					self._mapping[i] = (url_match, handler, other_params)

				if len(match.groupdict()) > 0:
					params = match.groupdict()
					for p in other_params:
						params.update(p)
					return handler, params

				else:
					return handler, (match.groups() + other_params)

		raise HandlerNotFoundException('cannt find url for %s' % req_script)
				
if __name__ == '__main__':
	pass
